#!/usr/bin/python -O

import sys, os

from qpid.messaging import Connection, Message, MessagingError

from amqp import RoutingKey
from protomsg import ProtoMsg

# -- main start here --
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-i','--ip',  dest = 'ip',
      action='store', default = '127.0.0.1',
      help='ip address of the broker, default [%default]')
parser.add_option('-p','--port',  dest = 'port',
      action='store',   type = int,  default = 5672,
      help='port of the broker, default [%default]')
parser.add_option('--proto-src',  dest ='protoSrc',
      action='store', default = os.path.join(os.environ['HOME'], 'protos'),
      help='directory to store subscribe, default [%default]')
parser.add_option('-k','--routing-key',  dest ='routing_key',
      action='store', help='routing key')
parser.add_option('-m','--message',  dest ='message',
      action='store', help='message to send')

(opts, args) = parser.parse_args()

if not opts.routing_key:
    print 'Parameter error, routing key must be provieded'
    sys.exit(1)

if opts.message is None:
    sys.exit(1)

broker = '%s:%d' % (opts.ip, opts.port)
address = 'amq.topic'

conn = Connection(broker)

try:
    conn.open()
    session = conn.session()
    sender = session.sender(address)

    rKey = RoutingKey(opts.routing_key)
    pMsg = ProtoMsg(opts.protoSrc, rKey.package, rKey.publication)

    pMsg.fill_from_string(opts.message)
    if __debug__:
        print 'Sending: %s' % pMsg.tojson

    msg = Message(properties = {'x-amqp-0-10.routing-key' : opts.routing_key},
                  content_type = 'application/x-protobuf',
                  content = pMsg.serialize_to_string())
    sender.send(msg)

except MessagingError, e:
        print e
        sys.exit(2)

finally:
    conn.close()
